package com.climb.ssm.util;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class BeanFactory {
	// 用于存放Bean对象的缓存，我们把它称之为容器
	private static Map<String, Object> container = new HashMap<String,Object>();

	static {
		try {
			Properties props = new Properties();
			//获取properties文件的流对象并加载配置内容到Propeties
			props.load(BeanFactory.class.getResourceAsStream("/bean.properties"));

			//取出配置文件中所有的Key
			Enumeration keys = props.keys();
			while (keys.hasMoreElements()){
				String key = keys.nextElement().toString();
				//获取全类名
				String beanClassName = props.getProperty(key);
				//反射创建对象
				Object value = Class.forName(beanClassName).getDeclaredConstructor().newInstance();
				//把key和value存入容器中
				container.put(key,value);
			}
		}catch(Exception e){
			throw new ExceptionInInitializerError("初始化容器失败！");
		}
	}

	// 根据Bean名称获取Bean对象
	public static Object getBean(String beanName){
		return container.get(beanName);
	}
}